package com.liuhao.ssm.controller;

import com.liuhao.ssm.annotation.AuthPassport;
import com.liuhao.ssm.annotation.Log;
import com.liuhao.ssm.domain.SysUser;
import com.liuhao.ssm.domain.UserInfo;
import com.liuhao.ssm.service.intf.SysUserService;
import com.liuhao.ssm.util.ResultData;
import com.liuhao.ssm.shiro.ShiroUtils;


import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;


/**
 * Created by liuHao on 2017/5/24.
 */
@Controller
@RequestMapping("")
public class LoginController extends BaseController {
    @Autowired
    private Producer defaultKaptcha;
    @Autowired
    private SysUserService sysUserService;

    @AuthPassport(value = false)
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = defaultKaptcha.createText();
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    @AuthPassport(value = false)
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    @Log(operationName = "登录", operationType = "用户登录系统")
    public ResultData login(String username, String password, String captcha) {
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            return ResultData.error("验证码不正确");
        }

        try {
            Subject subject = ShiroUtils.getSubject();
            //sha256加密
            password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            SysUser sysUser = sysUserService.queryByUserName(username);
            if (sysUser != null) {
                //加session
                UserInfo u = new UserInfo();
                //设置session
                u.setUserId(sysUser.getUserId());
                u.setUserName(sysUser.getUsername());
                ShiroUtils.setSessionAttribute("LoginInfo", u);
            }
        } catch (UnknownAccountException e) {
            return ResultData.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return ResultData.error(e.getMessage());
        } catch (LockedAccountException e) {
            return ResultData.error(e.getMessage());
        } catch (AuthenticationException e) {
            return ResultData.error("账户验证失败");
        }
        ResultData res = ResultData.ok("登录成功");
        return res;
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @Log(operationName = "登出", operationType = "用户退出系统")
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }

}
